package cn.li.security.service;


import cn.li.security.entity.Account;
import cn.li.security.repository.AccountRepository;
import cn.li.security.sms.ISmsUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;


@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService, ISmsUserDetailService {

    @Autowired
    private AccountRepository accountRepository;

    /**
     * 转换成userdetail
     * @param account
     * @return
     */
    private User covertFromAccount(Account account){
        User u= new User(account.getUsername(),account.getPassword(),
                //这里简单的把角色封装成鉴权列表，实际应用应当结合业务需求，将role->authority进行多对多的关系，进而进行转换
                account.getRoles().stream().map(item->new SimpleGrantedAuthority(item))
                        .collect(Collectors.toList())
        );
        return u;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findByUsername(username);
        if(account == null ){
            throw new UsernameNotFoundException(username + " not found");
        }
        return covertFromAccount(account);
    }
    @Override
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        Account account = accountRepository.findByPhone(phone);
        if(account == null ){
            throw new UsernameNotFoundException("ACCOUNT[" + phone +"] not found");
        }
        return covertFromAccount(account);
    }
    @Override
    public boolean testVerifyCode(String phone, String verifyCode) {
        log.info("accept {}|{}，this is  a mock service ， so it's alwalys return true" , phone,verifyCode);
        return true;
    }
}
